#!/usr/bin/env python3
# agv_logger.py
import queue
import os
import time
import threading
from datetime import datetime

class AGVLogger:
    def __init__(self, log_dir="logs"):
        # 确保日志目录存在
        self.log_dir = log_dir
        os.makedirs(log_dir, exist_ok=True)
        
        # 创建日志文件
        current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        self.log_file = os.path.join(log_dir, f"agv_log_{current_time}.txt")
        
        # 创建线程安全的日志队列
        self.log_queue = queue.Queue()
        self.is_running = True
        
        # 启动日志写入线程
        self.log_thread = threading.Thread(target=self._log_writer, daemon=True)
        self.log_thread.start()
        
        # 记录启动信息
        self.log(f"AGV系统启动 - 日志文件: {self.log_file}")
    
    def log(self, message):
        """添加日志消息到队列"""
        if not self.is_running:
            return
            
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_entry = f"[{timestamp}] {message}"
        
        try:
            self.log_queue.put(log_entry, block=False)
        except queue.Full:
            print("警告: 日志队列已满，无法添加新条目")
    
    def log_target_detection(self, target, confidence):
        """记录目标检测结果"""
        message = f"目标检测: {target} (置信度: {confidence:.4f})"
        self.log(message)
    
    def log_operation(self, operation_name, details=""):
        """记录机器人操作"""
        message = f"操作执行: {operation_name}"
        if details:
            message += f" - {details}"
        self.log(message)
    
    def log_voice_command(self, command_text):
        """记录语音命令"""
        self.log(f"语音命令: '{command_text}'")
    
    def log_system_event(self, event):
        """记录系统事件"""
        self.log(f"系统事件: {event}")
    
    def _log_writer(self):
        """日志写入线程"""
        print(f"日志线程启动，写入文件: {self.log_file}")
        
        # 创建日志文件并写入头信息
        with open(self.log_file, "w", encoding="utf-8") as f:
            f.write("=" * 60 + "\n")
            f.write(f"AGV系统日志 - 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write("=" * 60 + "\n\n")
        
        while self.is_running or not self.log_queue.empty():
            try:
                # 从队列获取日志条目
                log_entry = self.log_queue.get(timeout=1.0)
                
                # 追加写入文件
                with open(self.log_file, "a", encoding="utf-8") as f:
                    f.write(log_entry + "\n")
                
                # 标记任务完成
                self.log_queue.task_done()
                
            except queue.Empty:
                continue
            except Exception as e:
                print(f"日志写入错误: {e}")
        
        print("日志线程退出")
    
    def stop(self):
        """停止日志记录"""
        if not self.is_running:
            return
        
        self.is_running = False
        self.log("AGV系统关闭 - 日志记录结束")
        
        # 等待日志线程结束
        if self.log_thread.is_alive():
            self.log_thread.join(timeout=2.0)
        
        print("日志记录器已停止")
    
    def __del__(self):
        self.stop()